package com.fudan.es.aggs;

import java.util.List;
import java.util.Map;

import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fudan.es.Aggs;
import com.fudan.es.aggs.entity.ChartRequestEntity;
import com.fudan.es.aggs.entity.DimensionDef;
import com.fudan.es.aggs.entity.MetricDef;
import com.fudan.es.entity.DimensionPack;
import com.fudan.es.entity.FieldMeta;
import com.fudan.framework.utils.JsonUtils;


/**
 *
 * 格式：
 * {
 *  "dsId":"24"
 *	"dimension": {
 *		"type": "terms",
 *		"field": "1190"
 *	},
 *	"metric": [
 *		{
 *			"type": "count",
 *			"field": "739",
 *			"metric": [
 *				{
 *					"type": "avg",
 *					"field": "1183"
 *				},
 *				{
 *					"type": "count",
 *					"field": "1196"
 *				}
 *			]
 *		},
 *		{
 *			"type": "count",
 *			"field": "1192"
 *		}
 *	]
 * }
 *
 *
 * @author admin
 *
 */
@Component
public class RequestParser {

	@Autowired
	private MetricParser metricParser;
	@Autowired
	private DimensionParser dimensionParser;

	public Map<String,Object> buildMap(String json) throws Exception{
		Map<String,Object> reqMap = JsonUtils.toObject(json, Map.class);
		return reqMap;
	}

	public ChartRequestEntity buildRequestEntity(String json) throws Exception {
		return JsonUtils.toObject(json, new TypeReference<ChartRequestEntity>() {
		});
	}

	public DimensionPack buildPack(ChartRequestEntity req) {
		DimensionDef dimension = req.getDimension();
		List<MetricDef> metrics = req.getMetric();
		DimensionPack dimensionPack = null;
		if(dimension != null&& dimension.getField()!=null&&!"".equals(dimension.getField())) {
			dimensionPack = dimensionParser.build(dimension);
		}else {
			dimensionPack = DimensionPack.buildDefault();
		}
		if(metrics!=null) {
			for (MetricDef metric : metrics) {
				if(metric.getField()!= null&&!"".equals(metric.getField())) {
					dimensionPack.addMetric(metricParser.build(metric));
				}
			}
		}
		return dimensionPack;
	}

	public AggregationBuilder getAggregation(DimensionPack dimensionPack) throws Exception {
		FieldMeta dimensionField = dimensionPack.getField();
		if(dimensionField.getInNested()) {
			return Aggs.nested(dimensionField.getNestedPath(), dimensionField.getNestedPath()).subAggregation(dimensionPack.getRoot());
		}else {
			return dimensionPack.getRoot();
		}
	}

}
